package com.fhb.java.d20250609.动态代理;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author abao
 * @Description TODO
 * @createTime 2025-06-09 17:58:00
 */
public class 动态代理Proxy测试 {

    interface UserService{
        void login(String userName);
    }

    class UserServiceImpl implements UserService{

        @Override
        public void login(String userName) {
            System.out.println(String.format("%s has logined",userName));
        }
    }


    class UserServiceInvocationHandler implements InvocationHandler {
        private Object target;

        public UserServiceInvocationHandler(Object target){
            super();
            this.target = target;
        }


        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println(String.format("invoke method:%s start",method.getName()));
            Object result =  method.invoke(target, args);
            System.out.println(String.format("invoke method:%s end",method.getName()));
            return result;
        }

        public Object getProxy(){
            return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
        }
    }


    @Test
    public void test(){
        UserService userService = new UserServiceImpl();
        UserServiceInvocationHandler userServiceInvocationHandler = new UserServiceInvocationHandler(userService);
        UserService userServiceProxy = (UserService)userServiceInvocationHandler.getProxy();
        userServiceProxy.login("abao");
    }


}
